﻿using System;
using System.Windows.Forms;
using YougeBookmark.Services;
using YougeBookmark.Utilities;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Drawing;

namespace YougeBookmark.UI
{
    public partial class BookmarkForm : Form
    {
        private readonly BookmarkManager _bookmarkManager;
        private readonly TagManager _tagManager;
        private readonly ImageHelper _imageHelper;
        private readonly Logger _logger;
        private ParsedHtmlData _parsedData;
        private List<string> _selectedTags = new List<string>();

        public BookmarkForm(
            BookmarkManager bookmarkManager,
            TagManager tagManager,
            ImageHelper imageHelper,
            Logger logger)
        {
            _bookmarkManager = bookmarkManager;
            _tagManager = tagManager;
            _imageHelper = imageHelper;
            _logger = logger;

            InitializeComponent();
            SetupUI();
        }

        private void InitializeComponent()
        {
            // 基础布局配置
            this.SuspendLayout();
            this.ClientSize = new Size(600, 450);
            this.Text = "添加新书签";
            this.FormBorderStyle = FormBorderStyle.FixedDialog;

            // 缩略图显示
            this.pbThumbnail = new PictureBox
            {
                SizeMode = PictureBoxSizeMode.Zoom,
                Location = new Point(20, 20),
                Size = new Size(200, 150),
                BorderStyle = BorderStyle.FixedSingle
            };

            // 基础信息分组
            var gbInfo = new GroupBox
            {
                Text = "基本信息",
                Location = new Point(240, 20),
                Size = new Size(340, 200)
            };

            // 信息输入控件
            (this.txtTitle, var lblTitle) = CreateTextBox("标题:", 10, 30, 300);
            (this.txtUrl, var lblUrl) = CreateTextBox("URL:", 10, 70, 300, true);
            (this.txtSummary, var lblSummary) = CreateTextBox("摘要:", 10, 110, 300, true);
            (this.txtRemark, var lblRemark) = CreateTextBox("备注:", 10, 150, 300);

            // 标签管理分组
            var gbTags = new GroupBox
            {
                Text = "标签管理",
                Location = new Point(20, 190),
                Size = new Size(560, 150)
            };

            // 标签列表和按钮
            this.lstTags = new ListBox
            {
                Location = new Point(10, 20),
                Size = new Size(400, 120),
                SelectionMode = SelectionMode.MultiSimple
            };

            this.btnAddTag = new Button
            {
                Text = "+ 添加标签",
                Location = new Point(420, 20),
                Size = new Size(120, 30)
            };
            this.btnAddTag.Click += BtnAddTag_Click;

            // 操作按钮
            this.btnSave = new Button
            {
                Text = "保存",
                DialogResult = DialogResult.OK,
                Location = new Point(420, 380),
                Size = new Size(80, 30)
            };
            this.btnSave.Click += BtnSave_Click;

            this.btnCancel = new Button
            {
                Text = "取消",
                DialogResult = DialogResult.Cancel,
                Location = new Point(510, 380),
                Size = new Size(80, 30)
            };

            // 控件组合
            gbInfo.Controls.AddRange(new Control[] { txtTitle, txtUrl, txtSummary, txtRemark, lblTitle, lblUrl, lblSummary, lblRemark });
            foreach (Control ct in gbInfo.Controls)
            {
                ct.Location = new Point(ct.Location.X, ct.Location.Y + 8);
            }
            gbTags.Controls.AddRange(new Control[] { lstTags, btnAddTag });

            gbTags.Location = new Point(gbTags.Location.X, gbTags.Location.Y + 20);

            this.Controls.AddRange(new Control[] { pbThumbnail, gbInfo, gbTags, btnSave, btnCancel });

            this.ResumeLayout(false);
        }

        private void SetupUI()
        {
            // 初始化默认缩略图
            pbThumbnail.Image = Resources.Resources.default_thumbnail.BytesToImage();
        }

        public void InitializeData(ParsedHtmlData data)
        {
            _parsedData = data;

            // 填充解析数据
            txtTitle.Text = data.Title;
            txtUrl.Text = data.Url;
            txtSummary.Text = data.Summary;

            // 加载缩略图
            if (data.ImageData != null)
            {
                using var ms = new System.IO.MemoryStream(data.ImageData);
                pbThumbnail.Image = Image.FromStream(ms);
            }
        }

        private (TextBox, Label) CreateTextBox(string label, int x, int y, int width, bool readOnly = false)
        {
            var lbl = new Label
            {
                Text = label,
                Location = new Point(x, y - 18),
                AutoSize = true
            };

            var txt = new TextBox
            {
                Location = new Point(x, y),
                Size = new Size(width - 20, 20),
                ReadOnly = readOnly
            };

            return (txt, lbl);
        }

        #region 事件处理
        private async void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                var result = await _bookmarkManager.CreateBookmarkAsync(
                    _parsedData.Url,
                    _selectedTags,
                    txtRemark.Text
                );

                if (result != null)
                {
                    DialogResult = DialogResult.OK;
                    Close();
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"保存书签失败: {ex.Message}", ex);
                MessageBox.Show("保存失败: " + ex.Message);
            }
        }

        private void BtnAddTag_Click(object sender, EventArgs e)
        {
            var tagForm = Program.ServiceProvider.GetRequiredService<TagForm>();
            if (tagForm.ShowDialog() == DialogResult.OK)
            {
                // 刷新标签列表
                _selectedTags = tagForm.SelectedTags;
                lstTags.Items.Clear();
                lstTags.Items.AddRange(_selectedTags.ToArray());
            }
        }
        #endregion

        #region 控件声明
        private PictureBox pbThumbnail;
        private TextBox txtTitle;
        private TextBox txtUrl;
        private TextBox txtSummary;
        private TextBox txtRemark;
        private ListBox lstTags;
        private Button btnAddTag;
        private Button btnSave;
        private Button btnCancel;
        #endregion
    }
}